package com.ywb.ex10;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;

public class Test03 extends JFrame {
    Test03(){
        super("操纵表格");
        setBounds(100, 100, 500, 375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//        表格数据
        String[] columnNames = { "学号", "姓名", "性别", "年龄", "身高", " 体重", "血型" };
        Vector columnNameV = new Vector();
        for (int column = 0; column < columnNames.length; column++) {
            columnNameV.add(columnNames[column]);
        }
        Vector tableValueV = new Vector();
        for (int row = 1; row < 21; row++) {
            Vector rowV = new Vector();
            for (int column = 0; column < columnNames.length; column++)
            {
                rowV.add(columnNames[column] + row);
            }
            tableValueV.add(rowV);
        }

//        添加表格
        JTable table = new JTable(tableValueV, columnNameV);
        table.setRowSelectionInterval(1, 3);// 设置选中行
        table.addRowSelectionInterval(5, 5);
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
//        添加button
        JPanel buttonPanel = new JPanel();
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
        JButton selectAllButton = new JButton("全部选择");
        selectAllButton.addActionListener(e -> {
                table.selectAll();// 选中所有行
        });
        buttonPanel.add(selectAllButton);
        JButton clearSelectionButton = new JButton("取消选择");
        clearSelectionButton.addActionListener(e ->  {
                table.clearSelection();// 取消所有选中行的选择状态
        });
        buttonPanel.add(clearSelectionButton);
        System.out.println("表格共有" + table.getRowCount() + "行"
                + table.getColumnCount() + "列");
        System.out.println("共有" + table.getSelectedRowCount() + "行被选中");
        System.out.println("第3行的选择状态为：" + table.isRowSelected(2));
        System.out.println("第5行的选择状态为：" + table.isRowSelected(4));
        System.out.println("被选中的第一行的索引是：" + table.getSelectedRow());
        int[] selectedRows = table.getSelectedRows();// 获得所有被选中行的索引
        System.out.print("所有被选中行的索引是：");
        for (int row = 0; row < selectedRows.length; row++) {
            System.out.print(selectedRows[row] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new Test03().setVisible(true));

    }
}
